package com.cuit.mimall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cuit.mimall.entity.LoginUser;
import com.cuit.mimall.entity.User;
import com.cuit.mimall.service.IMenuService;
import com.cuit.mimall.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


/**
 * @author star
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final IUserService userService;
    private final IMenuService menuService;

    @Autowired
    public UserDetailsServiceImpl(IUserService userService, IMenuService menuService) {
        this.userService = userService;
        this.menuService = menuService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, username);
        User user = userService.getOne(wrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(user)) {
            throw new RuntimeException("没有该用户");
        }
        List<String> permissionKeyList = menuService.selectPermsByUserId(user.getUserId());
        //封装成UserDetails对象返回
        return new LoginUser(user, permissionKeyList);
    }
}
